package com.godfrey.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author godfrey
 * @since 2020-12-02
 */
@RestController
public class ConsumerController {

    private final DiscoveryClient discoveryClient;
    private final RestTemplate restTemplate;
    //访问服务提供者服务的前缀，http://服务名
    private static final String REST_URL_PREFIX = "http://provider";

    @Autowired
    public ConsumerController(DiscoveryClient discoveryClient, RestTemplate restTemplate) {
        this.discoveryClient = discoveryClient;
        this.restTemplate = restTemplate;
    }


    @GetMapping("/instances")
    public List<ServiceInstance> getInstances() {
        return discoveryClient.getInstances("provider");
    }

    //@GetMapping("/index")
    //public String index() {
    //    List<ServiceInstance> instances = discoveryClient.getInstances("provider");
    //    //随机访问服务
    //    int index = ThreadLocalRandom.current().nextInt(instances.size());
    //    String url = instances.get(index).getUri() + "/index";
    //    return "consumer随机远程调用provier：" + this.restTemplate.getForObject(url, String.class);
    //}

    @GetMapping("/index")
    public String index() {
        return "consumer远程调用provier：" + this.restTemplate.getForObject(REST_URL_PREFIX + "/index", String.class);
    }
}
